﻿using KinonekoSoftware.CodariaDB.Documents.Relationships;
using QuikGraph;

namespace KinonekoSoftware.Studio.Models.DataParts.Relationships
{
    public abstract class RelationshipSwitchable<T> : ObservableObject, IEdge<InstanceCache> where T : RelationCore
    {
        private InstanceCache _source;
        private InstanceCache _target;
        private bool          _isEditMode;
        
        protected virtual void OnUpdate()
        {
            
        }
        

        protected virtual void OnSwitchInstance()
        {

        }

        public void Update()
        {
            OnUpdate();
        }
        
        
        public void SetTargetID(string targetId) => Core.TargetID = targetId;


        public void GetInstance(InstanceCacheEngine engine)
        {
            //
            //
            if (!string.IsNullOrEmpty(Core.SourceID))
            {
                Source = engine.Get(InstanceType.Character, Core.SourceID);
            }


            //
            //
            if (!string.IsNullOrEmpty(Core.TargetID))
            {
                Target = engine.Get(InstanceType.Character, Core.TargetID);
            }


            RaiseUpdated(nameof(Source));
            RaiseUpdated(nameof(Target));
        }


        public void SwitchInstance()
        {

            InstanceSwitchFlag = !InstanceSwitchFlag;
            (_target, _source) = (_source, _target);

            OnSwitchInstance();
        }

        /// <summary>
        /// 判断当前的id是否为SourceID，如果不是则切换
        /// </summary>
        /// <param name="id">要判断的id。</param>
        public void SwitchInstance(string id)
        {
            if (Core.SourceID != id)
            {
                SwitchInstance();
            }
        }

        protected bool InstanceSwitchFlag    { get; set; }

        public T Core { get; init; }

        public bool IsEditMode
        {
            get => _isEditMode;
            set => SetValue(ref _isEditMode, value);
        }

        public InstanceCache Source
        {
            get => _source;
            set
            {
                _source       = value;
                RaiseUpdated();
            }
        }

        public InstanceCache Target
        {
            get => _target;
            set
            {
                _target       = value;
                Core.TargetID = value.Id;
                RaiseUpdated();
            }
        }
    }
}